package com.etalk.crm.controller;

import com.alibaba.fastjson.JSON;
import com.etalk.crm.client.InvokingService;
import com.etalk.crm.pojo.FormToken;
import com.etalk.crm.pojo.PaperTrackRecord;
import com.etalk.crm.pojo.Person;
import com.etalk.crm.pojo.QuestionBanks;
import com.etalk.crm.pojo.QuestionDifficultyDegree;
import com.etalk.crm.pojo.QuestionGrade;
import com.etalk.crm.pojo.QuestionTerm;
import com.etalk.crm.pojo.TestPaper;
import com.etalk.crm.pojo.TestPaperType;
import com.etalk.crm.pojo.User;
import com.etalk.crm.service.QuestionService;
import com.etalk.crm.service.TestPaperService;
import com.etalk.crm.service.YKNewMainService;
import com.etalk.crm.utils.RestResponseDTO;
import com.etalk.crm.utils.RestResponseStates;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.etalk.crm.utils.Constants.DEFAULT_PAGE_NUM;
import static com.etalk.crm.utils.Constants.DEFAULT_PAGE_SIZE;
import static com.etalk.crm.utils.Constants.PAPER_TRACK_STATUS_TRACK_FINISH;

/**
 * @author Terwer
 * @date 2018/04/28
 */
@Api(value = "试卷", tags = "试卷")
@Controller
@RequestMapping(value = "/testPaper")
public class TestPaperController {
    private static final Logger logger = LogManager.getLogger(TestPaperController.class);

    @Value("${static.server.url}")
    private String testStaticServerUrl;

    @Resource
    private TestPaperService testPaperService;

    @Resource
    private QuestionService questionService;

    @Resource
    private InvokingService invokingService;

    @Resource
    private YKNewMainService ykNewMainService;

    /**
     * 试卷列表页面
     *
     * @param model    Model
     * @param search   题目
     * @param pageNum  页码
     * @param pageSize 每页展示的数目
     * @return 试卷列表
     */
    @ApiOperation(value = "获取试卷列表", notes = "根据页码和每页展示的数目来获取试卷列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search", value = "题目", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页展示的数目", dataType = "Integer")
    })
    @RequestMapping(value = "/page/list", method = {RequestMethod.GET, RequestMethod.POST})
    public String getTestPaperList(Model model, Integer textbooksId, Integer unitId, Integer term, Integer gradeId, Integer state, String search, Integer pageNum, Integer pageSize) {
        if (search != null) {
            search = search.trim();
        }
        if (pageNum == null) {
            pageNum = DEFAULT_PAGE_NUM;
        }
        if (pageSize == null) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        if (state == null) {
            state = 1;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("textbooksId", textbooksId);
        paramMap.put("unitId", unitId);
        paramMap.put("term", term);
        paramMap.put("gradeId", gradeId);
        paramMap.put("state", state);
        paramMap.put("search", search);
        PageInfo<TestPaper> pageInfo = testPaperService.getTestPaperList(paramMap, pageNum, pageSize);
        if (pageInfo != null) {
            model.addAttribute("pageInfo", pageInfo);
        }
        List<QuestionGrade> listQGrade = questionService.selectQGradeList();
        model.addAttribute("listQGrade", listQGrade);
        // 获取单元
        List<QuestionTerm> listQuestionTerm = questionService.selectQuestionTermByParentTermId(0);
        model.addAttribute("listQuestionTerm", listQuestionTerm);
        model.addAttribute("textbooksId", textbooksId);
        model.addAttribute("unitId", unitId);
        model.addAttribute("term", term);
        model.addAttribute("gradeId", gradeId);
        model.addAttribute("state", state);
        model.addAttribute("search", search);
        model.addAttribute("testServerUrl", testStaticServerUrl);
        model.addAttribute("rnd", System.currentTimeMillis());
        return "testPaper/test_paper_list";
    }

    /**
     * 添加试卷页面
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "添加试卷页面", notes = "添加试卷页面")
    @FormToken(save = true)
    @RequestMapping(value = "/page/add", method = RequestMethod.GET)
    public String addPage(Model model) {
        //初始化下拉框
        initSelect(model);
        // 初始化页面数据
        initPage(model, 0);
        return "testPaper/test_paper_add";
    }


    /**
     * 试卷题目排序页面
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "试卷题目排序页面", notes = "试卷题目排序页面")
    @RequestMapping(value = "/page/question/sort/{paperId}", method = RequestMethod.GET)
    public String sortQuestion(Model model, @PathVariable("paperId") Integer paperId) {
        Integer isPaperDone = testPaperService.checkPaperHasDone(paperId) ? 1 : 0; // 0 未做过 1 做过
        model.addAttribute("isPaperDone", isPaperDone);
        return "testPaper/test_paper_sort_question";
    }

    /**
     * 修改试卷页面
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "修改试卷页面", notes = "修改试卷页面")
    @FormToken(save = true)
    @RequestMapping(value = "/page/edit/{paperId}", method = RequestMethod.GET)
    public String editPage(Model model, @PathVariable("paperId") Integer paperId) {
        //初始化下拉框
        initSelect(model);
        // 初始化页面数据
        initPage(model, paperId);
        return "testPaper/test_paper_add";
    }

    /**
     * 从题库选择题目
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "从题库选择题目", notes = "根据页码和每页展示的数目来获取试卷列表")
    @RequestMapping(value = "/page/chooseQuestion", method = RequestMethod.GET)
    public String chooseQuestionPage(Model model) {
        model.addAttribute("testServerUrl", testStaticServerUrl);
        model.addAttribute("rnd", System.currentTimeMillis());
        return "testPaper/test_paper_choose_question";
    }

    /**
     * 选择要发送试卷的学生
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "选择要发送试卷的学生", notes = "选择要发送试卷的学生")
    @RequestMapping(value = "/page/chooseStudent", method = RequestMethod.GET)
    public String chooseStudentPage(Model model, Integer testPaperId) {
        model.addAttribute("testPaperId", testPaperId);
        model.addAttribute("testServerUrl", testStaticServerUrl);
        model.addAttribute("rnd", System.currentTimeMillis());
        return "testPaper/test_paper_choose_student";
    }

    /**
     * @return
     */
    @ApiOperation(value = "链接分享", notes = "试卷链接分享")
    @RequestMapping(value = "/page/sendPaper", method = RequestMethod.GET)
    public String sendPaperPage() {
        return "testPaper/test_paper_send";
    }

    /**
     * 学生列表
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "学生列表", notes = "学生列表")
    @PostMapping(value = "/student/list", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getStudentList(Model model, String search, Integer pageNum, Integer pageSize) {
        if (search != null) {
            search = search.trim();
        }
        if (pageNum == null) {
            pageNum = DEFAULT_PAGE_NUM;
        }
        if (pageSize == null) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        PageInfo<Person> pageInfo = testPaperService.getStudentList(search, pageNum, pageSize);
        if (pageInfo != null) {
            model.addAttribute("pageInfo", pageInfo);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("page", pageNum);
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("rows", pageInfo.getList());
        return JSON.toJSONString(resultMap);
    }

    /**
     * 根据页码和每页展示的数目来获取学生做过的试卷列表
     *
     * @param model    model
     * @param search   题目
     * @param pageNum  页码
     * @param pageSize 每页展示的数目
     * @return 学生做过的试卷列表
     */
    @ApiOperation(value = "获取学生做过的试卷列表", notes = "根据页码和每页展示的数目来获取学生做过的试卷列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search", value = "题目", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页展示的数目", dataType = "Integer")
    })
    @RequestMapping(value = "/person/page/list", method = {RequestMethod.GET, RequestMethod.POST})
    public String getPersonPaperPage(
            Model model,
            Integer textbooksId,
            Integer unitId,
            Integer state,
            Integer paperTrackState,
            Integer term,
            Integer gradeId,
            String sendTime,
            String submitTime,
            String correctTime,
            String search,
            Integer pageNum,
            Integer pageSize,
            Integer sscId,
            HttpSession session) {
        if (search != null) {
            search = search.trim();
        }
        if (pageNum == null) {
            pageNum = DEFAULT_PAGE_NUM;
        }
        if (pageSize == null) {
            pageSize = DEFAULT_PAGE_SIZE;
        }

        int roleId = Integer.parseInt(session.getAttribute("roleId").toString());
        int loginId = Integer.parseInt(session.getAttribute("userid").toString());
        int storesId = Integer.parseInt(session.getAttribute("storesId").toString());
        model.addAttribute("roleId", roleId);
        List<User> sscList = null;
        if (roleId == 1 || roleId == 8 || roleId == 9) {
            sscList = ykNewMainService.searchSscByStoresId(storesId);
        }
        model.addAttribute("sscList", sscList);
        if ((null == sscId || sscId == 0) && (roleId == 8)) {
            sscId = loginId;
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("textbooksId", textbooksId);
        paramMap.put("unitId", unitId);
        paramMap.put("state", state);
        paramMap.put("paperTrackState", paperTrackState);
        paramMap.put("term", term);
        paramMap.put("gradeId", gradeId);
        paramMap.put("sendTime", sendTime);
        paramMap.put("submitTime", submitTime);
        paramMap.put("correctTime", correctTime);
        paramMap.put("sscId", sscId);
        paramMap.put("search", search);
        PageInfo<TestPaper> pageInfo = testPaperService.getSendedPaperListList(paramMap, pageNum, pageSize);
        if (pageInfo != null) {
            model.addAttribute("pageInfo", pageInfo);
            logger.info("获取到的学生以及试卷的信息：+" + JSON.toJSONString(pageInfo));
        }

        List<QuestionGrade> listQGrade = questionService.selectQGradeList();
        model.addAttribute("listQGrade", listQGrade);
        List<QuestionTerm> listQuestionTerm = questionService.selectQuestionTermByParentTermId(0); // 获取单元
        model.addAttribute("listQuestionTerm", listQuestionTerm);
        model.addAttribute("textbooksId", textbooksId);
        model.addAttribute("unitId", unitId);
        model.addAttribute("state", state);
        model.addAttribute("paperTrackState", paperTrackState);
        model.addAttribute("term", term);
        model.addAttribute("gradeId", gradeId);
        model.addAttribute("search", search);
        model.addAttribute("sendTime", sendTime);
        model.addAttribute("submitTime", submitTime);
        model.addAttribute("correctTime", correctTime);
        model.addAttribute("testServerUrl", testStaticServerUrl);
        model.addAttribute("sscId", sscId);
        model.addAttribute("rnd", System.currentTimeMillis());
        return "testPaper/test_paper_person_list";
    }

    /**
     * 获取学生做过的试卷列表
     *
     * @param tokenString 学生tokem
     * @param stateList   状态列表
     * @return 试卷信息
     */
    @ApiOperation(value = "获取学生做过的试卷列表", notes = "获取学生做过的试卷列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tokenString", value = "用户token", dataType = "String"),
            @ApiImplicitParam(name = "stateList", value = "状态列表", dataType = "String")
    })
    @ResponseBody
    @PostMapping(value = "/studentDone/list", produces = "application/json;charset=utf-8")
    public RestResponseDTO getTestPaperStudentDoneList(String tokenString, Integer personId, String stateList, HttpSession session) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        try {
            //获取试卷信息
            logger.info("获取试卷信息，tokenString为：" + tokenString + ",stateList:" + stateList);
            if (null == personId) {
                personId = (Integer) session.getAttribute("person.id");
            }
            Map resultMap = testPaperService.selectByStudentAndPage(personId, stateList, DEFAULT_PAGE_NUM, DEFAULT_PAGE_SIZE);
            if (!CollectionUtils.isEmpty(resultMap)) {
                restResponseDTO.setData(resultMap);
            } else {
                restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
                restResponseDTO.setMsg("暂无数据");
            }
            restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
            restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
        } catch (Exception e) {
            logger.error("studentDone list error:", e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        return restResponseDTO;
    }

    /**
     * 查询学生做题信息
     *
     * @param personId 用户ID
     * @param session  session
     * @return 做题结果页面
     */
    @ApiOperation(value = "查询学生做题信息", notes = "查询学生做题信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personId", value = "用户token", dataType = "String")
    })
    @RequestMapping(value = "/page/personDoneResult", method = RequestMethod.GET)
    public String getPersonDoneResult(Model model, Integer personId, Integer pageNum, Integer pageSize, HttpSession session) {
        logger.info("查询学生做题信息，personId：" + personId);
        if (pageNum == null) {
            pageNum = DEFAULT_PAGE_NUM;
        }
        if (pageSize == null) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        // PageInfo<TestPaper> pageInfo = testPaperService.getPaperListByPersonId(personId, pageNum, pageSize);
        // if (pageInfo != null) {
        //     model.addAttribute("pageInfo", pageInfo);
        //     logger.info("获取到的学生以及试卷的信息：+" + JSON.toJSONString(pageInfo));
        // }
        model.addAttribute("testServerUrl", testStaticServerUrl);
        model.addAttribute("rnd", System.currentTimeMillis());
        model.addAttribute("personId", personId);
        return "testPaper/person_done_result";
    }

    @ApiOperation(value = "查询试卷中题目ID列表", notes = "查询试卷中题目ID列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tokenString", value = "required，用户token", dataType = "String"),
            @ApiImplicitParam(name = "personId", value = "用户ID，如果不传则取tokenString里面的personId", dataType = "Integer"),
            @ApiImplicitParam(name = "testPaperId", value = "试卷ID", dataType = "Integer"),
            @ApiImplicitParam(name = "scoreId", value = "分数ID", dataType = "Integer"),
            @ApiImplicitParam(name = "isUnderstand", value = "是否掌握", dataType = "Integer"),
            @ApiImplicitParam(name = "isCorrected", value = "手动批改时候标记是否批改（qmodeId=11,13），0未批改，-1所有", dataType = "Integer"),
            @ApiImplicitParam(name = "isTrue", value = "是否做对，0错题，1正确的题目，-1所有", dataType = "Integer"),
            @ApiImplicitParam(name = "isPager", value = "默认0部分页，1分页", dataType = "Integer"),
            @ApiImplicitParam(name = "pageNumber", value = "页码，默认1", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页展示的数目，默认10", dataType = "Integer")
    })
    @PostMapping(value = "/question/info", produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResponseDTO getTestPaperQuestionInfo(String tokenString, Integer personId, Integer questionId, Integer testPaperId, Integer scoreId, Integer isUnderstand, Integer isCorrected, Integer isTrue, Integer isPager, Integer pageNumber, Integer pageSize, HttpSession session) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        try {
            logger.info("查询试卷中题目ID列表，tokenString：" + tokenString + ",testPaperId:" + testPaperId);
            // 获取试卷信息
            if (null == personId) {
                personId = (Integer) session.getAttribute("person.id");
            }
            Map paramMap = new HashMap();
            paramMap.put("testPaperId", testPaperId);
            paramMap.put("scoreId", scoreId);
            paramMap.put("isUnderstand", isUnderstand);
            paramMap.put("personId", personId);
            paramMap.put("isCorrected", isCorrected);
            paramMap.put("isTrue", isTrue);

            // 组装结果
            Map<String, Object> resultMap = new HashMap<>();
            List<Map> qbankInfoList;
            if (null != isPager && isPager == 1) {
                if (pageNumber == null) {
                    pageNumber = DEFAULT_PAGE_NUM;
                }
                if (pageSize == null) {
                    pageSize = DEFAULT_PAGE_SIZE;
                }
                PageInfo pageInfo = testPaperService.getTestPaperQuestionInfoByPage(paramMap, pageNumber, pageSize);
                qbankInfoList = pageInfo.getList();
                resultMap.put("qcount", pageInfo.getTotal());
            } else {
                qbankInfoList = testPaperService.getTestPaperQuestionInfo(paramMap);
                resultMap.put("qcount", qbankInfoList.size());
            }
            resultMap.put("qlist", qbankInfoList);
            if (testPaperId > 0) {
                TestPaper testPaper = testPaperService.selectBasicInfoByTestPaperIdAndScoreId(testPaperId, scoreId);
                resultMap.put("paperInfo", testPaper);
            } else {
                resultMap.put("paperInfo", null);
            }
            restResponseDTO.setData(resultMap);
            restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
            restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
        } catch (Exception e) {
            logger.error("查询试卷中题目ID列表异常,error=" + e.getMessage(), e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        return restResponseDTO;
    }

    @ApiOperation(value = "查询试卷中单个题目的信息", notes = "查询试卷中单个题目的信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tokenString", value = "用户token", dataType = "String"),
            @ApiImplicitParam(name = "qbankId", value = "题目ID", dataType = "Integer"),
            @ApiImplicitParam(name = "scoreId", value = "分数ID", dataType = "Integer")
    })
    @PostMapping(value = "/questionItem", produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResponseDTO getTestPaperQuestionItemInfo(String tokenString, Integer qbankId, Integer scoreId) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        try {
            logger.info("查询试卷中单个题目的信息，tokenString：" + tokenString + ",qbankId:" + qbankId);
            // 获取有做题结果的题目信息
            QuestionBanks result = questionService.selectByQuestionIdAndScoreId(qbankId, scoreId);

            restResponseDTO.setData(result);
            restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
            restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
        } catch (Exception e) {
            logger.error("查询试卷中单个题目的信息异常,error=" + e.getMessage(), e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        return restResponseDTO;
    }

    /**
     * 试卷提交
     *
     * @param formData
     * @return
     */
    @ApiOperation(value = "生成试卷提交", notes = "生成试卷提交")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "TestPaper", value = "TestPaper", required = false, dataType = "TestPaper")
    })
    @FormToken(remove = true)
    @PostMapping(value = "/submit", produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResponseDTO submit(@RequestBody TestPaper formData) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        boolean flag = false;
        try {
            logger.info("生成或者修改试卷：入参=" + JSON.toJSONString(formData));
            flag = testPaperService.saveTestPaper(formData);
        } catch (Exception e) {
            logger.error("系统异常" + e.getLocalizedMessage(), e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        //操作失败
        if (!flag) {
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        } else {
            restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
            restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
        }
        restResponseDTO.setData(null);
        return restResponseDTO;
    }

    @PostMapping(value = "/sendPaperToStudent", produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResponseDTO sendPaperToStudent(String tokenString, Integer testPaperId, Integer personId) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        boolean flag = false;
        try {
            logger.info("开始生成试卷：入参=testPaperId->" + testPaperId + "studentId->" + personId);
            boolean isEnableToSend = testPaperService.checkTestState(testPaperId, personId);
            logger.info("检查是否可以做试卷结果：isEnableToSend=" + isEnableToSend);
            if (!isEnableToSend) {//不允许再次测试
                restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
                restResponseDTO.setMsg("该用户上次对本试卷的测评还未完成，不允许测试本试卷，请先在试卷批改完成该试卷");
                return restResponseDTO;
            } else {
                Integer scoreId = testPaperService.sendPaperToStudent(testPaperId, personId);
                if (scoreId > 0) {
                    // 试卷发送成功，发送微信通知
                    TestPaper paperInfo = testPaperService.getBasicInfoByTestPaperId(testPaperId);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    String sendDate = sdf.format(new Date());
                    invokingService.sendDoingPapersMessage(personId, paperInfo.getPaperName(), sendDate);

                    // 返回结果
                    flag = true;
                    Map dataMap = new HashMap();
                    dataMap.put("scoreId", scoreId);
                    restResponseDTO.setData(dataMap);
                }
            }
        } catch (Exception e) {
            logger.error(e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        //操作失败
        if (!flag) {
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg("试卷发送失败，请重试");
        } else {
            restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
            restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
        }
        return restResponseDTO;
    }

    /**
     * 删除试卷
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "删除试卷", notes = "删除试卷")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "testPaperId", value = "试卷ID", required = false, dataType = "Integer"),
    })
    @FormToken(remove = true)
    @GetMapping(value = "/delete/{testPaperId}", produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResponseDTO deletePaper(Model model, @PathVariable("testPaperId") Integer testPaperId) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        boolean flag = false;
        try {
            flag = testPaperService.deleteTestPaper(testPaperId);
            //操作失败
            if (!flag) {
                restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
                restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
            } else {
                restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
                restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
            }
        } catch (Exception e) {
            logger.error(e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        restResponseDTO.setData(null);
        return restResponseDTO;
    }

    @ApiOperation(value = "修改试卷状态", notes = "修改试卷状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tokenString", value = "用户token", dataType = "String"),
            @ApiImplicitParam(name = "scoreId", value = "分数ID", dataType = "int"),
            @ApiImplicitParam(name = "state", value = "状态：0未做，1待批改，2未讲解完，3已讲解完", dataType = "int")
    })
    @PostMapping(value = "/changePaperState")
    @ResponseBody
    public RestResponseDTO changePaperState(String tokenString, Integer scoreId, Integer state) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        boolean flag = false;
        try {
            logger.info("修改试卷状态：入参tokenString=" + tokenString + ",scoreId=" + scoreId + ",state=" + state);
            flag = testPaperService.changePaperState(scoreId, state);
        } catch (Exception e) {
            logger.error("试卷状态修改失败", e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        //操作失败
        if (!flag) {
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        } else {
            restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
            restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
        }
        restResponseDTO.setData(null);
        return restResponseDTO;
    }

    /**
     * 发送试卷给绑定该教材的学生
     *
     * @param tokenString 学生tokem
     * @param testPaperId 试卷ID
     * @return 结果
     */
    @ApiOperation(value = "发送试卷给绑定该教材的学生", notes = "发送试卷给绑定该教材的学生")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tokenString", value = "用户token", dataType = "String"),
            @ApiImplicitParam(name = "testPaperId", value = "试卷ID", dataType = "String")
    })
    @ResponseBody
    @PostMapping(value = "/sendPaperToLearnTextbook", produces = "application/json;charset=utf-8")
    public RestResponseDTO sendPaperToLearnTextbook(String tokenString, Integer testPaperId, HttpSession session) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        try {
            //获取试卷信息
            logger.info("获取试卷信息，tokenString为：" + tokenString + ",testPaperId:" + testPaperId);
            Integer personId = (Integer) session.getAttribute("person.id");
            boolean flag = testPaperService.batchSaveTestPaperScoresByTextbook(testPaperId);
            if (flag) {
                restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
                restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
            } else {
                restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
                restResponseDTO.setMsg("发送异常");
            }
        } catch (Exception e) {
            logger.error("sendPaperToLearnTextbook error:", e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        return restResponseDTO;
    }

    /**
     * 修改跟进状态
     *
     * @param tokenString
     * @param scoreId
     * @param session
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/changeTrackStatus", produces = "application/json;charset=utf-8")
    public RestResponseDTO changeTrackStatus(String tokenString, Integer scoreId, HttpSession session) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        try {
            boolean flag = testPaperService.updatePaperTrackStatus(scoreId, PAPER_TRACK_STATUS_TRACK_FINISH);
            if (flag) {
                restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
                restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
            } else {
                restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
                restResponseDTO.setMsg("跟进异常");
            }
        } catch (Exception e) {
            logger.error("changeTrackStatus error:", e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        return restResponseDTO;
    }

    @ApiOperation(value = "更新跟进记录", notes = "更新跟进记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperTrackRecord", value = "跟进记录,state:跟进状态（0无需跟进，1待跟进，2已跟进）", dataType = "PaperTrackRecord"),
            @ApiImplicitParam(name = "tokenString", value = "用户token", dataType = "String")
    })
    @PostMapping(value = "/updatePaperTrackRecord", produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResponseDTO updatePaperTrackRecord(@RequestBody PaperTrackRecord paperTrackRecord, String tokenString, HttpSession session) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        boolean flag = false;
        try {
            logger.info("添加跟进记录：入参paperTrackRecord=" + JSON.toJSONString(paperTrackRecord));
            flag = testPaperService.updatePaperTrackRecord(paperTrackRecord);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        //操作失败
        if (!flag) {
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        } else {
            restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
            restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
        }
        restResponseDTO.setData(null);
        return restResponseDTO;
    }

    @ApiOperation(value = "修改试卷题目排序", notes = "修改试卷题目排序")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sortInfo", value = "排序信息", dataType = "Map"),
            @ApiImplicitParam(name = "tokenString", value = "用户token", dataType = "String")
    })
    @PostMapping(value = "/updatePaperQuestionSort", produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResponseDTO updatePaperQuestionSort(@RequestBody Map<String, Object> sortInfo, String tokenString, HttpSession session) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        boolean flag = false;
        try {
            logger.info("修改试卷题目排序：入参sortInfo=" + JSON.toJSONString(sortInfo));
            flag = testPaperService.updatePaperQuestionSort(sortInfo);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        //操作失败
        if (!flag) {
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        } else {
            restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
            restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
        }
        restResponseDTO.setData(null);
        return restResponseDTO;
    }

    /**
     * 试卷启用禁用
     */
    @ApiOperation(value = "试卷启用禁用", notes = "试卷启用禁用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperId", value = "试卷ID"),
            @ApiImplicitParam(name = "state", value = "状态：0禁用，1启用")
    })
    @FormToken(remove = true)
    @PostMapping(value = "/changePaperAvailableState", produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResponseDTO changePaperAvailableState(Integer paperId, Integer state) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        boolean flag = false;
        try {
            logger.info("试卷启用禁用：入参paperId=" + paperId + ",state=" + state);
            flag = testPaperService.changePaperAvailableState(paperId, state);
        } catch (Exception e) {
            logger.error("系统异常" + e.getLocalizedMessage(), e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        //操作失败
        if (!flag) {
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        } else {
            restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
            restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
        }
        restResponseDTO.setData(null);
        return restResponseDTO;
    }

    /**
     * 初始化下拉框
     *
     * @param model model
     */
    private void initSelect(Model model) {
        List<TestPaperType> listPaperType = testPaperService.selectPaperTypeList();
        List<QuestionDifficultyDegree> listQDifficultyDegree = questionService.selectQDifficultyDegreeList();
        List<QuestionGrade> listQGrade = questionService.selectQGradeList();
        // 获取单元
        List<QuestionTerm> listQuestionTerm = questionService.selectQuestionTermByParentTermId(0);

        model.addAttribute("listPaperType", listPaperType);
        model.addAttribute("listQDifficultyDegree", listQDifficultyDegree);
        model.addAttribute("listQGrade", listQGrade);
        model.addAttribute("listQuestionTerm", listQuestionTerm);
    }

    /**
     * 初始化页面数据
     *
     * @param model   model
     * @param paperId 试卷ID
     */
    private void initPage(Model model, Integer paperId) {
        TestPaper testPaper = null;
        if (paperId != null && paperId > 0) {
            try {
                testPaper = testPaperService.getBasicInfoByTestPaperId(paperId);
            } catch (Exception e) {
                logger.error("试卷信息查询失败", e);
            }
        } else {
            testPaper = new TestPaper();
        }
        model.addAttribute("paper", testPaper);
        model.addAttribute("paperId", paperId);
    }
}
